import { PageContainer } from '@ant-design/pro-components';
import { Button, message, Modal, Space, Table, Input, Switch,Divider  } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined ,EyeOutlined} from '@ant-design/icons';
import type { FC } from 'react';
import { useState, useEffect } from 'react';
import { useNavigate } from 'umi';
import {
  deptpage,
  deptDelete,
  deptUpdateStatus
} from '@/services/system/departmentmanage';
import { useOutletContext } from '@umijs/max';
import AuthorizedButton from '@/components/AuthorizedButton';
interface DepartmentType {
  id: string;
  departmentName: string;
  description: string;
  departmentType: number;
  sort: number;
  status: number;
  createTime: string;
  children?: DepartmentType[];
  fatherDepartmentId: string | null;
}
interface ButtonData {
  id: string;
  pageId: string;
  resourceName: string;
  icon?: string;
  action: string;
}
const DepartmentManage: FC = () => {
  const navigate = useNavigate();
  const [departments, setDepartments] = useState<DepartmentType[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const { buttonData } = useOutletContext<{ buttonData: ButtonData[] }>();
  const [searchText, setSearchText] = useState('');

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async (params = {}) => {
    try {
      const response = await deptpage({
        current: params?.current || 1,
        size: params?.pageSize || 10,
       ...params
      });

      if (response.code === 200) {
        let filteredData = response.data.records;
        if (searchText) {
          // 根据输入的搜索文本进行过滤，这里以userName字段为例，可按需调整
          filteredData = filteredData.filter(record => record.userName.includes(searchText));
        }

        setDepartments(filteredData);
      }
    } catch (error) {
      console.error(error);
    }
  };
  const columns = [
    {
      title: '部门名称',
      dataIndex: 'departmentName',
    },
    {
      title: '部门描述',
      dataIndex: 'description',
    },
    {
      title: '部门类型',
      dataIndex: 'departmentType',
    },
    {
      title: '部门排序',
      dataIndex: 'sort',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (_, record) => (
        <Switch
          checkedChildren="启用"
          unCheckedChildren="禁用"
          checked={record.status === 0}
          onChange={(checked) => handleStatusChange(record.id, checked)}
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <span>
        <Space split={<Divider type="vertical" />}>
          <AuthorizedButton
            buttonData={buttonData}
            action="edit"
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
            style={{
              padding: 0,
              height: '22px',
              lineHeight: '22px',
            }}
          >
            编辑
          </AuthorizedButton>
          <AuthorizedButton
            buttonData={buttonData}
            action="delete"
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
            style={{
              padding: 0,
              height: '22px',
              lineHeight: '22px',
              // backgroundColor:'red'
            }}
          >
            删除
          </AuthorizedButton>
          <AuthorizedButton
            buttonData={buttonData}
            action="view"
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
            style={{
              padding: 0,
              height: '22px',
              lineHeight: '22px',
            }}
          >
            详情
          </AuthorizedButton>
        </Space>
      </span>
      ),
    },
  ];

  const handleAdd = () => {
    navigate('/system/departmentmanage/add');
  };

  const handleEdit = (record: DepartmentType) => {
    navigate('/system/departmentmanage/edit', { state: { record } });
  };

  const handleView = (record: DepartmentType) => {
    navigate('/system/departmentmanage/view', { state: { record } });
  };

  const handleDelete = (record: DepartmentType) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除部门 "${record.departmentName}" 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await deptDelete({
            id: record.id
          });

          if (response.code === 200) {
            message.success('删除成功');
            fetchData(); // 刷新列表
          } else {
            message.error(response.msg || '删除失败');
          }
        } catch (error) {
          console.error('删除失败:', error);
          message.error('删除失败');
        }
      }
    });
  };

  const handleStatusChange = async (id: string, checked: boolean) => {
    try {
      const response = await deptUpdateStatus({
        id,
        status: checked ? 0 : 1  // 0 表示启用，1 表示禁用
      });

      if (response.code === 200) {
        message.success('状态修改成功');
        fetchData(); // 刷新列表数据
      } else {
        message.error(response.msg || '状态修改失败');
      }
    } catch (error) {
      console.error('状态修改失败:', error);
      message.error('状态修改失败');
    }
  };

  const rowSelection = {
    type: 'checkbox',
    selectedRowKeys,
    onChange: (selected: React.Key[]) => {
      setSelectedRowKeys(selected);
    },
    checkStrictly: true,
    columnWidth: 60,
    columnTitle: '选择',
    getCheckboxProps: (record: DepartmentType) => ({
      name: record.id,
    }),
  };

  const convertToTableData = (data: DepartmentType[]): DepartmentType[] => {
    const map = new Map();
    const result: DepartmentType[] = [];

    // 第一步：将所有节点添加到 map 中
    data.forEach(item => {
      map.set(item.id, { ...item, children: [] });
    });

    // 第二步：建立父子关系
    data.forEach(item => {
      const node = map.get(item.id);
      if (!item.fatherDepartmentId) {
        result.push(node);
      } else {
        const parentNode = map.get(item.fatherDepartmentId);
        if (parentNode) {
          if (!parentNode.children) {
            parentNode.children = [];
          }
          parentNode.children.push(node);
        }
      }
    });

    // 第三步：移除空的 children 数组
    const removeEmptyChildren = (nodes: DepartmentType[]) => {
      return nodes.map(node => {
        if (node.children && node.children.length === 0) {
          const { children, ...rest } = node;
          return rest;
        }
        if (node.children) {
          return {
            ...node,
            children: removeEmptyChildren(node.children)
          };
        }
        return node;
      });
    };

    return removeEmptyChildren(result);
  };

  const onExpand = (expanded: boolean, record: DepartmentType) => {
    if (expanded) {
      setExpandedKeys(prev => [...prev, record.id]);
    } else {
      setExpandedKeys(prev => prev.filter(key => key !== record.id));
    }
  };

  return (
    <PageContainer>
      <Space style={{ marginBottom: 16 }}>
      <AuthorizedButton
          buttonData={buttonData}
          action="add"
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleAdd}
        >
          新增
        </AuthorizedButton>
      </Space>

      <Table
        columns={columns}
        dataSource={departments}
        rowKey="id"
        rowSelection={rowSelection}
        expandable={{
          expandedRowKeys: expandedKeys,
          onExpand: onExpand,
          defaultExpandAllRows: false,
          expandRowByClick: true,
        }}
      />
    </PageContainer>
  );
};

export default DepartmentManage;
